package com.youchuang.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.youchuang.action.cart.CartItem;
import com.youchuang.bean.Indent;
import com.youchuang.bean.IndentItem;
import com.youchuang.bean.ReceiveAddress;
import com.youchuang.common.Constant;
import com.youchuang.dao.IndentDAO;
import com.youchuang.dao.IndentItemDAO;
import com.youchuang.dao.ReceiveAddressDAO;
import com.youchuang.service.IndentService;
import com.youchuang.util.Md5CodeUtil;

@Transactional
@Service("indentService")
public class IndentServiceImpl implements IndentService {

	@Resource
	private ReceiveAddressDAO receiveAddressDAO;
	@Resource
	private IndentDAO indentDAO;
	@Resource
	IndentItemDAO indentItemDAO;

	public IndentServiceImpl() {
	}

	public List<ReceiveAddress> findReceiveAddressByUserId(String userId) {
		return receiveAddressDAO.queryByUserId(userId);
	}

	public String indentPayVerify(String IndentId, String bankRadio, String passWord, String pass) {
		// TODO: 如何进行网页的密码进行加密
		// TODO：密码的加密
		Indent indent = indentDAO.queryById(IndentId);
		if (pass.equals(Md5CodeUtil.createMd5Code(passWord))) {
			indent.setPaymentMethod(bankRadio);
			indent.setStatus(Constant.WAIT_SHIP);
			indentDAO.update(indent);
			return Constant.SUCCESS;
		}
		return Constant.ERROR;
	}

	public void saveIndent(List<CartItem> cartItems, Indent indent, ReceiveAddress receiveAddress) {
		if (receiveAddressDAO.queryById(receiveAddress.getId()) == null)
			receiveAddressDAO.save(receiveAddress);
		indentDAO.save(indent);
		for (CartItem cartItem : cartItems) {
			IndentItem indentItem = new IndentItem();
			indentItem.setIndentId(indent.getId());
			indentItem.setProductId(cartItem.getProduct().getId());
			indentItem.setUserId(receiveAddress.getUserId());
			indentItem.setProductName(cartItem.getProduct().getProductName());
			indentItem.setDangPrice(cartItem.getProduct().getDangPrice());
			indentItem.setProductNum(cartItem.getNum());
			indentItem.setAmount(cartItem.getProduct().getDangPrice() * cartItem.getNum());
			indentItem.setProductPic(cartItem.getProduct().getProductPic());
			indentItemDAO.save(indentItem);
		}
	}

	public Indent findIndentById(String id) {
		return indentDAO.queryById(id);
	}

	public List<Indent> findIndentByUserId(String userId) {
		return indentDAO.queryByUserIdDESC(userId);
	}

	public List<IndentItem> findIndentItemByIndentId(String indentId) {
		return indentItemDAO.queryByIndentId(indentId);
	}
	
	public List<IndentItem> findIndentItemByUserId(String userId) {
		return indentItemDAO.queryByUserId(userId);
	}

	public void updateIndent(String id, int status) {
		Indent indent = indentDAO.queryById(id);
		indent.setStatus(status);
		indentDAO.update(indent);
	}

}
